<?php

namespace App\Http\Controllers;

use App\Helpers\ResponseData;
use App\Models\ConfigTable;
use Illuminate\Http\Request;
use Modules\Manager\Entities\Manager;
use Illuminate\Support\Facades\DB;

class ConfigController extends Controller
{
    use ResponseData;
    public function list(ConfigTable $model,Request $request){
        if ($request->filled('key')&&$request->key=='cqrykey') {
            $users = Manager::query()->where('post_id',3)->get();
            $data = [];
            foreach ($users as $k => $item) {
                $map = [
                    'id' => $item->id,
                    'name' => $item->nick_name,
                    'phone' => $item->phone,
                ];
                array_push($data, $map);
            }
            return $this->success(json_encode($data));
        } else {
            $size = $request->input('size',50);
            if($request->filled('key')){
                $data = $model->where('key',$request->key)->value('value');
                return $this->success($data);
            }
            if($request->filled('status')&&$request->status=='all'){
                $data = $model->orderBy('id','desc')->get();
            }else{
                $data = $model->orderBy('id','desc')->paginate($size);
            }
            return $this->success($data);
        }
    }
    public function store(ConfigTable $model,Request $request){
        $data = $request->all();
        $model->fill($data);
        $model->save();
        return $this->success('保存成功');
    }
    public function edit(ConfigTable $model,Request $request){
        $data = $model->find($request->id);
        return $this->success($data);
    }
    public function update(ConfigTable $model,Request $request){
        // 有ID用ID更新，没ID用key更新
        if($request->filled('id')){
            $data = $model->find($request->id);
            $data->update($request->all());
        }elseif($request->filled('key')){
            $data = $model->where('key',$request->key)->first();
            $data->update($request->all());
        }
        return $this->success('修改成功');
    }
    public function destory(ConfigTable $model,Request $request){
        $data = $model->find($request->id);
        $data->delete();
    }
    public function addsystemlog(Request $request){
        $data = $request->all();
        DB::table('system_logs')->insert($data);
        return $this->success('添加日志成功');
    }
}
